package com.xiaoluo.web;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoluo.cd.entity.base.Commits;
import com.xiaoluo.cd.entity.base.Jobs;
import com.xiaoluo.cd.entity.base.Projects;
import com.xiaoluo.cd.entity.base.Servers;
import com.xiaoluo.common.enums.JobStatusEnum;
import com.xiaoluo.common.enums.JobTypeEnum;
import com.xiaoluo.common.enums.ServerTypeEnum;
import com.xiaoluo.common.queue.JobQueue;
import com.xiaoluo.common.utils.Shell;
import com.xiaoluo.service.CommitService;
import com.xiaoluo.service.JobService;
import com.xiaoluo.service.ProjectService;
import com.xiaoluo.service.ServerService;
import com.xiaoluo.web.form.GitCommit;
import com.xiaoluo.web.form.GitProject;
import com.xiaoluo.web.form.ProjectForm;
import com.xiaoluo.web.form.ResultForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Project : SpiderManager
 * Package : com.xiaoluo.web
 * Created by Willian.
 * Date  : 2015/10/21 20:29.
 */
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController{
    private final static Logger logger = LoggerFactory.getLogger(ProjectController.class);

    @Autowired
    private ProjectService projectService;
    @Autowired
    private ServerService serverService;
    @Autowired
    private CommitService commitService;
    @Autowired
    private JobService jobService;

    private ObjectMapper mapper = new ObjectMapper();

    @RequestMapping(value = "/list")
    public  String list(ModelMap model,String keyword){

        List<Projects> projectses = projectService.list();

        model.addAttribute("projects",projectses);
        return "project/list";
    }

    @RequestMapping(value = "/settings",method = RequestMethod.GET)
    public  String settings(ModelMap model,Long id){
        logger.info("request parameter id ={}",id);

        if(id != null){
            ProjectForm projects = projectService.findById(id);
            List<Servers> testServers = serverService.queryByType(ServerTypeEnum.TEST.getValue());
            List<Servers> productServers = serverService.queryByType(ServerTypeEnum.PRODUCT.getValue());
            model.addAttribute("project",projects);
            model.addAttribute("testServers",testServers);
            model.addAttribute("productServers",productServers);
        }

        return "project/setting";
    }

    @RequestMapping(value = "/commits",method = RequestMethod.GET)
    public  String commits(ModelMap model,@RequestParam Long id,Long commitId){
        logger.info("request parameter id ={}",id);

        if(id != null){
            ProjectForm projects = projectService.findById(id);
            List<Commits> list = commitService.list(id,commitId);

            model.addAttribute("list",list);
            model.addAttribute("project",projects);
        }

        return "project/commit";
    }
    @RequestMapping(value = "/charts",method = RequestMethod.GET)
    public  String charts(ModelMap model,@RequestParam Long id){
        logger.info("request parameter id ={}",id);

        if(id != null){
            ProjectForm projects = projectService.findById(id);
            model.addAttribute("project",projects);
        }

        return "project/setting";
    }
    @RequestMapping(value = "/variables",method = RequestMethod.GET)
    public  String variables(ModelMap model,@RequestParam Long id){
        logger.info("request parameter id ={}",id);

        if(id != null){
            ProjectForm projects = projectService.findById(id);
            model.addAttribute("project",projects);
        }

        return "project/variables";
    }
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public  String save(ModelMap model,Projects projects,String testServer,String productServer){

        logger.info("parameters test:{},product:{}",testServer,productServer);
        projectService.save(projects,testServer,productServer);
        return "forward:list";
    }
    /**
     * 项目构建
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/build")
    public  String build(ModelMap model,@RequestParam Long id,HttpServletRequest request){
        /**
         * 1、新建job;
         * 2、提交任务;
         * 3、返回任务列表

        logger.info("request parameter id ={}",id);

        if(id != null){
            Projects projects = projectService.get(id);
            Commits commits = commitService.findByProj(projects.getId());
            //提交任务
            jobService.submit(projects,commits);
            //获取任务列表
            List<Jobs> jobsList = jobService.list(id, (int) JobTypeEnum.BUILD.getValue(), null, null,null);
            model.addAttribute("project",projects);
            model.addAttribute("jobs",jobsList);
        }
         */
        return "project/jobs";
    }


    /**
     * gitlab web hook function.
     * @param params
     * @return
     */
    @RequestMapping(value = "/callback",produces = "application/json; charset=UTF-8")
    @ResponseBody
    public ResultForm callback(@RequestBody String params){
        logger.info(params);

        ResultForm result = new ResultForm(0,"success.");
        try {
            GitProject project =  mapper.readValue(params, GitProject.class);
            projectService.saveGitProject(project);
            Projects projects = projectService.getByGit(project.getRepository().getGit_ssh_url());
            GitCommit gitCommit = commitService.save(project, projects.getId());
            Commits commits = commitService.get(gitCommit.getId());
            /**
             * 自动构建

            if(projects.getAutoBuild()==1){
                jobService.submit(projects,commits);
            }*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


}
